<?php
// 应用公共文件

/**
 * 获取路由
 * @return array
 * @author ^2_3^王尔贝
 */
function getRoute()
{
    $route = [];

    $rule = \think\facade\Request::rule()->getRoute();
    preg_match_all('/app\\\(\w+)\\\controller\\\(\w+)@(\w+)/', $rule, $ruleMatches);
    if( count( $ruleMatches ) != 4 ) {
        return $route;
    }
    $appName = app('http')->getName();
    $controllerName = $ruleMatches['2'][0];
    $methodName = $ruleMatches['3'][0];
    $route = [
        'rule' => "{$appName}/{$controllerName}/{$methodName}",
        'is_admin' => $appName == 'admin',
    ];
    return $route;
}

/**
 * json返回格式封装
 *
 * @param string $msg
 * @param int $code
 * @param array $data
 * @param bool $is_continue
 * @return \think\response\Json
 * @author ^2_3^王尔贝
 */
function retJson($msg = '', $code = 0, $data = [], $is_continue = false)
{
    $data = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'request_id' => \app\Log::getRequestId(),
        // 'route' => getRoute(),
    ];

    $header = [];
    $route = getRoute();
    if( !empty( $route ) && $route['is_admin'] ) {
        $header = [
            'acm' => $route['rule'],
        ];
    }

    if( !$is_continue ) {
        return json( $data, 200, $header );

    }else {
        json( $data, 200, $header )->send();
    }

}

/**
 * lo
 * @param $logMsg
 * @param string $type
 * @author ^2_3^王尔贝
 */
function lo($logMsg, $type = 'error')
{
    \think\facade\Log::record($logMsg, $type);
}

/**
 * 删除文件
 * @param string $file
 * @return bool
 * @author ^2_3^王尔贝
 */
function delFile($file = '')
{
    if (stripos($file, 'http') > -1) {
        $urlArr = parse_url($file);
        $filePath = $urlArr['path'];
    }else {
        $filePath = $file;
    }
    $filePath = PUBLIC_PATH . $filePath;

    if (is_file($filePath)) {
        unlink($filePath);
        return true;
    }

    return false;
}

/**
 * getPassword
 * @param string $password
 * @param int $salt
 * @return string
 * @author ^2_3^王尔贝
 */
function getPassword($password = '', $salt = 0)
{
    $pass = '';
    if (empty($password) || empty($salt)) {
        return $pass;
    }

    $pass = md5( $password.'?43?23?11?'.md5('?'.$salt) );

    return $pass;
}
